package com.morty.config;

import cn.hutool.core.date.SystemClock;
import com.github.structlog4j.StructLog4J;
import com.github.structlog4j.json.JsonFormatter;
import com.morty.config.filter.LogInterceptor;
import com.morty.config.utils.IpUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.PostConstruct;

/**
 * @title: LogAutoConfig
 * @description:
 */

@Configuration
public class LogAutoConfig implements WebMvcConfigurer {

    @Value("${spring.application.name:NA}")
    private String appName;


    @PostConstruct
    public void init() {

        StructLog4J.setFormatter(JsonFormatter.getInstance());
        StructLog4J.setMandatoryContextSupplier(() -> new Object[]{
                "host", IpUtils.getHostIp(),
                "appName", appName,
                "logTime", SystemClock.nowDate()
        });

    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        /**
         * 自定义拦截器，添加拦截路径和排除拦截路径
         * addPathPatterns():添加需要拦截的路径
         * excludePathPatterns():添加不需要拦截的路径
         * 在括号中还可以使用集合的形式，如注释部分代码所示
         */
        registry.addInterceptor(new LogInterceptor()).addPathPatterns("/**");


    }


}
